﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics;

namespace Mp4BoxModelNS
{
    class Mp4BoxModel
    {
        public delegate void OutputHandler(string outStr);
        public event OutputHandler outputHandler;
        
        private string mp4BoxPath;
        private string audioPath;
        private string videoPath;
        private string outputPath;

        private string addVideoArgs;
        public string VideoArgs
        {
            get { return addVideoArgs; }
            set { addVideoArgs = value; }
        }
        private string addAudioArgs;
        public string AudioArgs
        {
            get { return addAudioArgs; }
            set { addAudioArgs = value; }
        }

        public Mp4BoxModel(string mp4BoxPth, string videoPth, string audioPth, string outputPth) {
            mp4BoxPath = mp4BoxPth;
            audioPath = audioPth;
            videoPath = videoPth;
            outputPath = outputPth;
        }

        public void createArgs(string fps, string par, bool sbr) {
            addVideoArgs = String.Format("\"{0}\" -add \"{1}\":fps={2}:par={3}", outputPath, videoPath, fps, par);
            if (sbr) {
                addAudioArgs = String.Format("\"{0}\" -add \"{1}\":sbr", outputPath, audioPath);
            } else {
                addAudioArgs = String.Format("\"{0}\" -add \"{1}\"", outputPath, audioPath);
            }
        }

        public void startCoding() {
            ProcessStartInfo start = new ProcessStartInfo();
            start.FileName = mp4BoxPath;
            start.UseShellExecute = false;
            start.RedirectStandardOutput = true;

            start.Arguments = addVideoArgs;
            start.CreateNoWindow = true;
            
            //Console.WriteLine(addVideoArgs);
            using (Process process = Process.Start(start))
            {
                using (StreamReader reader = process.StandardOutput)
                {
                    string result;
                    while ((result = reader.ReadLine()) != null)
                    {
                        outputHandler(result + "\n");
                        //Console.WriteLine(result);
                    }
                }
            }

            start.Arguments = addAudioArgs;
            using (Process process = Process.Start(start))
            {
                using (StreamReader reader = process.StandardOutput)
                {
                    string result;
                    while ((result = reader.ReadLine()) != null)
                    {
                        outputHandler(result + "\n");
                        //Console.WriteLine(result);
                    }
                }
            }
        }


    }
}
